package com.study.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.common.exception.ApiException;
import com.study.common.utils.GenerateUtils;
import com.study.common.utils.StringUtils;
import com.study.modules.sys.mapper.SysRoleMapper;
import com.study.modules.sys.mapper.SysUserMapper;
import com.study.modules.sys.mapper.SysUserRoleMapper;
import com.study.modules.sys.model.dto.SysUserDTO;
import com.study.modules.sys.model.entity.SysRole;
import com.study.modules.sys.model.entity.SysUser;
import com.study.modules.sys.service.SysUserRoleService;
import com.study.modules.sys.service.SysUserService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import static com.study.common.utils.PubFinalData.*;

/**
 * @Author Mr.Du
 * @Date 2021/10/16 10:52
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public IPage<SysUserDTO> selectUserList(String status, Page<SysUser> page) {
        IPage<SysUserDTO> sysUserList = userMapper.selectUserList(status,page);
        //循环查询角色信息
        for (SysUserDTO sysUser : sysUserList.getRecords()) {
            List<Long> roleIdList = userRoleMapper.selectRoleIdListByUserId(sysUser.getId());
            if (roleIdList != null && roleIdList.size() > 0) {
                List<SysRole> roleList = new ArrayList<>();
                for (Long roleId : roleIdList) {
                    SysRole sysRole = roleMapper.selectRoleById(roleId);
                    roleList.add(sysRole);
                }
                sysUser.setRoleList(roleList);
            }
        }

        return sysUserList;
    }

    @Override
    public SysUser selectUserByLoginName(String loginName) {
        SysUser user = userMapper.selectByLoginName(loginName);
        if (user == null) throw new ApiException("用户不存在");
        if (user.getDeleted().equals(1) || user.getStatus().equals(1)) {
            throw new ApiException("用户被禁用或被删除！");
        }
        return user;
    }

    @Override
    public SysUser selectUserById(Long id) {
        SysUser user = userMapper.selectUserById(id);
        if (user == null) throw new ApiException("用户不存在！");
        return user;
    }

    @Override
    public SysUser selectPsdSaltById(Long userId){
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("id",userId);
        SysUser sysUser = baseMapper.selectOne(wrapper);
        if (sysUser == null || sysUser.getDeleted().equals(DELETED)) throw new ApiException("用户不存在！");
        return sysUser;
    }

    @Override
    public SysUser selectPsdSaltByLoginName(String loginName){
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name",loginName);
        SysUser sysUser = baseMapper.selectOne(wrapper);
        if (sysUser == null || sysUser.getDeleted().equals(DELETED)) throw new ApiException("用户不存在！");
        return sysUser;
    }

    @Override
    public SysUserDTO selectUserInfo(Long userId) {
        SysUser sysUser = selectUserById(userId);
        SysUserDTO userDTO = new SysUserDTO();
        BeanUtils.copyProperties(sysUser, userDTO);

        //查询角色信息
        List<SysRole> roleList = userRoleService.selectRoleListByUserId(sysUser.getId());
        if (roleList != null && roleList.size() > 0) {
            userDTO.setRoleList(roleList);
        }
        return userDTO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insert(SysUserDTO sysUser) {
        //对象类型转化
        SysUser sysUser2 = new SysUser();
        BeanUtils.copyProperties(sysUser, sysUser2);
        SysUser sysUser1 = userMapper.selectByLoginName(sysUser2.getLoginName());
        if (sysUser1 != null) throw new ApiException("用户名已存在，无法新增！");
        if (sysUser2.getUserType() == null) {
            sysUser2.setUserType(SYS_USER_TYPE_COMMON);
        }
        //sha256加密
        String salt = GenerateUtils.generateRandomSalt(null);
        sysUser2.setStatus(SYS_USER_STATUS_NORMAL);
        sysUser2.setDeleted(UN_DELETED);
        sysUser2.setSalt(salt);
        sysUser2.setPassword(new Sha256Hash(sysUser2.getPassword(), salt).toHex());
        sysUser2.setCreateTime(new Date());
        userMapper.insert(sysUser2);
        //添加角色关联
        if (sysUser.getRoleIdList() != null && !sysUser.getRoleIdList().trim().equals("")) {
            String roleIdString = sysUser.getRoleIdList();
            Long[] convert = (Long[]) ConvertUtils.convert(roleIdString.split(","), Long.class);
            List<Long> roleIdList = Arrays.asList(convert);
            SysUser sysUser3 = userMapper.selectByLoginName(sysUser2.getLoginName());
            //跟新添加角色
            userRoleService.insertOrUpdate(sysUser3.getId(), roleIdList);
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByWeb(SysUserDTO sysUser, Long userId) {
        SysUser sysUser1 = new SysUser();
        BeanUtils.copyProperties(sysUser, sysUser1);
        //根据用户名查询数据库用户信息
        SysUser dbUser = selectPsdSaltById(sysUser1.getId());

        if (dbUser == null || dbUser.getDeleted().equals(1)) throw new ApiException("用户不存在或已删除，无法修改用户密码！");
        if (!dbUser.getLoginName().equals(sysUser1.getLoginName())) throw new ApiException("用户名禁止修改！");

        String password = new Sha256Hash(sysUser1.getPassword(), dbUser.getSalt()).toHex();
        if (!password.equals(dbUser.getPassword())) {
            sysUser1.setPassword(password);
        } else {
            sysUser1.setPassword(dbUser.getPassword());
        }
        sysUser1.setUpdateId(userId);
        sysUser1.setUpdateTime(new Date());
        userMapper.updateById(sysUser1);
        //添加角色关联
        if (sysUser.getRoleIdList() != null && !sysUser.getRoleIdList().trim().equals("")) {
            String roleIdString = sysUser.getRoleIdList();
            //字符串转化list
            List<Long> roleIdList = StringUtils.covertListByStr(roleIdString);
            //跟新添加角色
            userRoleService.insertOrUpdate(sysUser1.getId(), roleIdList);
        }
        return true;
    }

    @Override
    public Boolean resetPassword(Long userId, Long operatorId){
        SysUser sysUser = selectPsdSaltById(userId);
        String dbSalt = sysUser.getSalt();
        String password = new Sha256Hash("123456", dbSalt).toHex();
        sysUser.setPassword(password);
        sysUser.setUpdateId(operatorId);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        return true;
    }

    @Override
    public Boolean updatePsd(String oldPassword, String newPassword, Long userId) {
        SysUser sysUser = baseMapper.selectUserById(userId);
        if (sysUser == null || sysUser.getStatus().equals(SYS_USER_STATUS_DISABLE))
            throw new ApiException("用户不存在或被禁用，无法修改密码！");

        if (oldPassword == null || oldPassword.trim().equals("")) throw new ApiException("旧密码为空");
        if (newPassword == null || newPassword.trim().equals("")) throw new ApiException("新密码为空");
        //传入的旧密码加密
        String oldSaltPassword = new Sha256Hash(oldPassword, sysUser.getSalt()).toHex();
        //传入的新密码加密
        String newSaltPassword = new Sha256Hash(newPassword, sysUser.getSalt()).toHex();
        if (!oldSaltPassword.equals(sysUser.getPassword())) throw new ApiException("旧密码不正确，无法修改！");
        if (oldSaltPassword.equals(newSaltPassword)) throw new ApiException("您的旧密码和新密码一样，无法修改！");
        sysUser.setPassword(newSaltPassword);
        sysUser.setUpdateId(userId);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        return true;
    }

    @Override
    public Boolean disableUser(Long userId, Integer status, Long operatorId) {
        SysUser sysUser = baseMapper.selectUserById(userId);
        if (sysUser == null) throw new ApiException("用户不存在，无法更改用户状态！");
        if (status == null) throw new ApiException("请传入用户状态！");
        if (status.equals(SYS_USER_STATUS_NORMAL) || status.equals(SYS_USER_STATUS_DISABLE)) {
            sysUser.setStatus(status);
            sysUser.setUpdateId(operatorId);
            sysUser.setUpdateTime(new Date());
            baseMapper.updateById(sysUser);
            return true;
        }
        throw new ApiException("状态不合规，无法更改");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delete(Long userId, Long operatorId) {
        SysUser sysUser = baseMapper.selectUserById(userId);
        if (sysUser == null) throw new ApiException("用户不存在，无法删除！");
        //删除用户角色关联
        userRoleService.deleteUserRoleByUserId(userId);
        //删除用户
        sysUser.setDeleted(DELETED);
        sysUser.setUpdateId(operatorId);
        sysUser.setUpdateTime(new Date());
        baseMapper.updateById(sysUser);
        return true;
    }


}
